package org.millioncall.yueyoga.common.security;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

//自定义访问决策器
public class ZhuwAccessDecisionManager implements AccessDecisionManager {
	// 判断用户是否具有访问此资源的权限
	// 本函数中的参数configAttributes是通过MySecurityMetadataSource类的getAttributes方法取得的
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if (configAttributes == null) {
			return;// 所访问资源无访问权限定义，直接放行
		}
		Iterator<ConfigAttribute> iterator = configAttributes.iterator();// 允许访问此资源的权限列表
		while (iterator.hasNext()) {// 遍历此权限列表，用户拥有其中一项权限即可
			ConfigAttribute configAttribute = iterator.next();
			String needPermission = configAttribute.getAttribute();// 权限名称
			for (GrantedAuthority ga : authentication.getAuthorities()) {// 遍历用户所拥有的权限
				if (ga.getAuthority().equals(needPermission)) {// 用户拥有所访问资源的权限，放行
					return;
				}
			}
		}
		throw new AccessDeniedException("您无权访问本页面，请联系管理员");
	}

	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}
}